<?php

namespace app\user\controller\order;

use app\common\controller\Backend;
use app\common\controller\Frontend;
use hehe\Trade;
use think\facade\Db;

/**
 * 下单操作
 */
class PlaceOrder extends Frontend {
    /**
     * Order模型对象
     * @var object
     * @phpstan-var \app\admin\model\order\Order
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\user\model\order\Order;
    }


    /**
     * 生成订单
     */
    public function generateOrder(){
        $param = $this->request->param();
//        print_r($param);die;
        $order = db::name('order')->where(['user_id' => $this->auth->id, 'type' => $param['type']])->whereNull('out_trade_no')->find();
        if(!$order) $this->error('没有待生成的订单记录');
        $order_goods = db::name('order_goods')->where(['order_id' => $order['id']])->whereNull('place_order_time')->find();
        if(!$order_goods) $this->error('没有待生成的订单记录');
        Db::startTrans();
        try{

            $order_update = [
                'out_trade_no' => Trade::generateTradeNo(),
                'place_order_time' => $this->timestamp,
                'anchor_name' => empty($param['anchor_name']) ? '' : $param['anchor_name'],
                'live_time' => empty($param['live_time']) ? null : strtotime($param['live_time']),
            ];
            db::name('order')->where(['id' => $order['id']])->update($order_update);
            $order_goods_update = [
                'place_order_time' => $this->timestamp,
                'update_time' => $this->timestamp
            ];
            db::name('order_goods')->where(['order_id' => $order['id']])->update($order_goods_update);

            db::commit();
        }catch (\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('已生成订单，请选择您接下来的操作');
    }


    /**
     * 生成临时订单
     */
    public function generateTempOrder(){
        $param = $this->request->param();
//        print_r($param);die;
        Db::startTrans();
        try{
            $where = [
                'user_id' => $this->auth->id,
                'type' => $param['type']
            ];
            $order = db::name('order')->where($where)->whereNull('out_trade_no')->find();
            if($order){
                $order_id = $order['id'];
            }else{
                $insert_order = [
                    'user_id' => $this->auth->id,
                    'type' => $param['type'],
                ];
                $order_id = Db::name('order')->insertGetId($insert_order);
            }

            $insert_order_goods = [];
            $field = "g.id, g.goods_brand_id, g.supply_price";
            $goods = db::name('goods')->alias('g')->field($field)
                ->leftJoin('goods_brand b', 'g.goods_brand_id = b.id')
                ->whereIn('g.id', $param['ids'])->select();

            $brandResult = Db::name('user_brand_profit')->where(['user_id' => $this->auth->id])->select();


            $brand = [];
            foreach($brandResult as $val){
                $brand[$val['brand_id']] = $val['profit'];
            }
            foreach($goods as $val){
                $order_goods = Db::name('order_goods')->where(['goods_id' => $val['id']])->whereNull('place_order_time')->find();
                if(!$order_goods){
                    $specs = db::name('goods_specs')->where(['goods_id' => $val['id']])->find();
                    $purchase_price = $val['supply_price'] + $brand[$val['goods_brand_id']];
                    $insert_order_goods[] = [
                        'order_id' => $order_id,
                        'goods_id' => $val['id'],
                        'num' => 1,
                        'color' => $specs['color'],
                        'size' => $specs['size'],
                        'purchase_price' => $purchase_price,
                        'total_price' => $purchase_price * 1
                    ];
                }

            }
            if($insert_order_goods){
                db::name('order_goods')->insertAll($insert_order_goods);
            }

            $orderTotalPrice = db::name('order_goods')->where(['order_id' => $order_id])->sum('total_price');
            $order_update = [
                'total_price' => $orderTotalPrice,
                'update_time' => $this->timestamp
            ];
            db::name('order')->where(['id' => $order_id])->update($order_update);

            db::commit();
        }catch (\Exception $e){
            db::rollback();
//            $this->error($e->getMessage() . ' --- ' . $e->getLine());
            $this->error($e->getMessage());
        }
        $this->success();
    }


    /**
     * 修改临时订单的数量
     */
    public function updateOrderGoodsTempNum(): void{
        $param = $this->request->param();
        $row = db::name('order_goods')->where(['id' => $param['id']])->find();
        if($row['status'] != 0) $this->error('当前订单状态无法修改数量');
        $update = [
            'num' => $param['num'],
            'total_price' => $param['num'] * $row['purchase_price'],
            'update_time' => $this->timestamp
        ];

        $result = Db::name('order_goods')->where(['id' => $param['id']])->update($update);
        if($result){
            $this->success('', [
                'total_price' => number_format($update['total_price'])
            ]);
        }else{
            $this->error();
        }
    }


    /**
     * 客户的直播商品列表
     */
    public function index(): void {

        $param = $this->request->param();
//        print_r($param);die;
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
//        echo 1;die;

        $brand_id = $param['brand_id'];
        $model = new \app\admin\model\order\OrderGoods();
        $user_id = $this->auth->id;

        $brand_result = db::name('user_brand_profit')->where(['user_id' => $user_id])->select();
        $brand = [];
        foreach($brand_result as $val){
            $brand[$val['brand_id']] = $val['profit'];
        }

        $res = $model->with(['brand', 'goods', 'orders'])->group('goods_id')->alias($alias);

        $keyword = empty($param['quickSearch']) ? null : $param['quickSearch'];
        if(empty($brand_id)){
            if($keyword){
                $res->hasWhere('goods', function($query) use ($keyword){
                    $query->where('name', 'like', '%' . $keyword . '%');
                });
            }
        }else{
            if($keyword){
                $res->hasWhere('goods', function($query) use ($keyword, $brand_id){
                    $query->where('name', 'like', '%' . $keyword . '%')->where(['goods_brand_id' => $brand_id]);
                });
            }else{
                $res->hasWhere('goods', function($query) use ($brand_id){
                    $query->where(['goods_brand_id' => $brand_id]);
                });
            }
        }

        $res = $res->whereNotNull('OrderGoods.place_order_time')->hasWhere('orders', ['user_id' => $user_id])->order($order)->paginate($limit);
        $list = $res->items();

        foreach($list as $key => $val){
            $list[$key]['goods']['user_price'] = number_format($val['goods']['supply_price'] + $brand[$val['goods']['goods_brand_id']]);
            $list[$key]['goods']['price'] = number_format($val['goods']['price']);
            $list[$key]['goods']['supply_price'] = number_format($val['goods']['supply_price']);
        }




        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}